﻿using System.Collections.Generic;
using BitButterCORE.Object;

namespace BitButterCORE.Factory
{
	public class TokenFactory : BaseFactory<BaseToken, TokenFactory>
	{
		public override void RemoveObject(BaseToken obj)
		{
			base.RemoveObject(obj);

			if (Factory.Count == 0)
			{
				ResumeInterruptedApplierMethods();
			}
		}

		public override void ClearFactory()
		{
			base.ClearFactory();
			ResumeInterruptedApplierMethods();
		}

		public bool HasObject => Factory.Count > 0;

		public void InterruptApplierMethod(InterruptedApplierMethod interruptedApplierMethod)
		{
			if (interruptedApplierMethod != null)
			{
				InterruptedApplierMethods.Add(interruptedApplierMethod);
			}
		}

		void ResumeInterruptedApplierMethods()
		{
			foreach (var interruptedApplierMethod in InterruptedApplierMethods)
			{
				interruptedApplierMethod.Method.Invoke(interruptedApplierMethod.Rule, interruptedApplierMethod.Parameters);
			}
			InterruptedApplierMethods.Clear();
		}

		List<InterruptedApplierMethod> InterruptedApplierMethods => interruptedApplierMethods ?? (interruptedApplierMethods = new List<InterruptedApplierMethod>());
		List<InterruptedApplierMethod> interruptedApplierMethods;
	}
}
